package com.xiaoming.backend.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.util.Date;

@Component
public class JwtUtil {
    @Value("${jwt.secret}")
    private String secret;

    @Value("${jwt.expiration}")
    private long expiration;

    private SecretKey getSigningKey() {
        return Keys.hmacShaKeyFor(secret.getBytes());
    }

    public String generateToken(String username,  Long institutionId) {
        return Jwts.builder()
                .subject(username)  // 新版API
                .claim("institutionId", institutionId)
                .issuedAt(new Date())  // 新版API
                .expiration(new Date(System.currentTimeMillis() + expiration))  // 新版API
                .signWith(getSigningKey())  // 无需指定算法，自动推断
                .compact();
    }

    public Claims parseToken(String token) {
        return Jwts.parser()
                .verifyWith(getSigningKey())  // 新版API
                .build()
                .parseSignedClaims(token)  // 新版API
                .getPayload();

    }

    public boolean validateToken(String token, String username) {
        final String tokenUsername = parseToken(token).getSubject();
        return (username.equals(tokenUsername) && !isTokenExpired(token));
    }

    private boolean isTokenExpired(String token) {
        return parseToken(token).getExpiration().before(new Date());
    }
}
